package cn.virens.common.oauth.service.cookie;

import cn.virens.common.util.core.network.RequestUtil;
import cn.virens.common.util.exception.APIException;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.hutool.core.reflect.method.MethodUtil;
import org.springframework.session.web.http.DefaultCookieSerializer;

import java.util.Optional;

public class VirensCookieSerializer extends DefaultCookieSerializer {
    private String cookieName; // cookie名称

    /**
     * 从请求中获取cookie内容(如果不存在从请求头中获取)
     */
    public Optional<String> readCookieValue(HttpServletRequest request) throws APIException {
        return Optional.ofNullable(RequestUtil.getCookies(request, cookieName)).or(() -> {
            return Optional.ofNullable(request.getHeader(cookieName));
        });
    }

    /**
     * 获取cookie中的值
     */
    public String getValue0(CookieValue cookieValue) throws APIException {
        return MethodUtil.invoke(this, "getValue", cookieValue);
    }

    /**
     * 将cookie内容直接写到响应头
     */
    public void writeHeadValue(CookieValue ck) throws APIException {
        ck.getResponse().addHeader(getCookieName(), getValue0(ck));
    }

    @Override
    public void setCookieName(String cookieName) {
        super.setCookieName(cookieName);
        this.cookieName = cookieName;
    }

    public String getCookieName() {
        return cookieName;
    }
}
